//
//  NewsSpeechManager.m
//  suRead
//
//  Created by lidi on 2018/6/3.
//  Copyright © 2018年 bao. All rights reserved.
//

#import "NewsSpeechManager.h"
#import "M_News.h"
#import "ServiceNews.h"
#import "M_NewsDetail.h"
#import "SpeechManager.h"
#import "NewsSpeechStatusView.h"
#import "Masonry.h"
#import "UIApplication+VisibleViewController.h"
#import "NewsDetailViewController.h"

@interface NewsSpeechManager()

@property (nonatomic,strong) NSMutableArray *newsList;
@property (nonatomic,strong) NSMutableArray *removedNewsList;
@property (nonatomic,strong) M_News *current;

@property (nonatomic,strong) M_NewsDetail *newsDetail;

@property (nonatomic,strong) NSMutableArray *detailStatusViews;

@end

@implementation NewsSpeechManager

+ (instancetype)shared
{
    static NewsSpeechManager *sharedManager = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedManager = [self new];
        sharedManager.detailStatusViews = [NSMutableArray array];
    });
    return sharedManager;
}

//MARK: - statusView
- (void)showStatusView {
    if (!self.statusView) {
        self.statusView = [[[NSBundle mainBundle] loadNibNamed:@"NewsSpeechStatusView" owner:self options:nil] lastObject];
        self.statusView.layer.cornerRadius = 20.0f;
        self.statusView.layer.masksToBounds = YES;
    }
    
    UINavigationController *controller = (UINavigationController *)[[UIApplication sharedApplication] keyWindow].rootViewController;
    UIViewController *c = [controller.viewControllers objectAtIndex:0];
    [c.view addSubview:self.statusView];
    //[[[UIApplication sharedApplication] keyWindow].rootViewController.view addSubview:self.statusView];
    [self.statusView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@40.0f);
        make.left.equalTo(self.statusView.superview).offset(15.0f);
        make.right.equalTo(self.statusView.superview).offset(-15.0f);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.statusView.superview.mas_safeAreaLayoutGuideBottom).offset(-15.0f - 49.0f);
        } else {
            // Fallback on earlier versions
            make.bottom.equalTo(self.statusView.superview).offset(-15.0f - 49.0f);
        }
    }];
    
    __weak typeof(self) weakSelf = self;
    [self.statusView setHandle:^{
        [[SpeechManager shared] cancel];
        [weakSelf.newsList removeAllObjects];
        weakSelf.newsList = [NSMutableArray array];
        [weakSelf.removedNewsList removeAllObjects];
        weakSelf.removedNewsList = [NSMutableArray array];
        [weakSelf removeStatusView];
    } next:^{
        if ([SpeechManager shared].isPlayDetail) {
            [[SpeechManager shared] cancel];
            [weakSelf speechNewsDetail:weakSelf.newsDetail];
        } else {
            [[SpeechManager shared] cancel];
            [weakSelf autoSpeechNext];
        }
    } pre:^{
        //上一个新闻
        [weakSelf preSpeech];
    } play:^{
        if ([SpeechManager shared].isPlayDetail) {
            [weakSelf speechNewsDetail:weakSelf.newsDetail];
        } else {
            [weakSelf speech:weakSelf.newsList];
        }
    } tap:^{
        //跳转新闻详情
        UIViewController *controller = [[UIApplication sharedApplication] visibleViewController];
        if ([controller isKindOfClass:[NewsDetailViewController class]]) {
            //当前已经是详情页面
            if ([SpeechManager shared].isPlayDetail) {
                if ([controller isKindOfClass:[NewsDetailViewController class]] && [[(NewsDetailViewController *)controller urlString] isEqualToString:weakSelf.newsDetail.urlString]) {
                    //不作操作
                } else {
                    NewsDetailViewController *con = [NewsDetailViewController new];
                    con.urlString = weakSelf.newsDetail.urlString;
                    con.f_thumbnail = weakSelf.newsDetail.f_thumbnail;                   con.hidesBottomBarWhenPushed = YES;
                    [controller showViewController:con sender:nil];
                }
            } else {
                if ([self.newsList count] >0) {
                    M_News *news_ = [weakSelf.newsList objectAtIndex:0];
                    NewsDetailViewController *controller = [NewsDetailViewController new];
                    controller.hidesBottomBarWhenPushed = YES;
                    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                    controller.f_thumbnail = news_.f_thumbnail;
                    [[[UIApplication sharedApplication] visibleViewController] showViewController:controller sender:nil];
                }
            }
        } else {
            //当前不是详情页
            if ([SpeechManager shared].isPlayDetail) {
                NewsDetailViewController *con = [NewsDetailViewController new];
                con.urlString = weakSelf.newsDetail.urlString;
                con.f_thumbnail = weakSelf.newsDetail.f_thumbnail;
                con.hidesBottomBarWhenPushed = YES;
                [controller showViewController:con sender:nil];
            } else {
                if ([self.newsList count] >0) {
                    M_News *news_ = [weakSelf.newsList objectAtIndex:0];
                    NewsDetailViewController *controller = [NewsDetailViewController new];
                    controller.hidesBottomBarWhenPushed = YES;
                    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                    controller.f_thumbnail = news_.f_thumbnail;
                    [[[UIApplication sharedApplication] visibleViewController] showViewController:controller sender:nil];
                }
            }
            
        }
        
 
    }];
    
    if ([[[UIApplication sharedApplication] visibleViewController] isKindOfClass:[NewsDetailViewController class]]) {
        NewsSpeechStatusView *stView = [[[NSBundle mainBundle] loadNibNamed:@"NewsSpeechStatusView" owner:self options:nil] lastObject];
        stView.layer.cornerRadius = 20.0f;
        stView.layer.masksToBounds = YES;
        
        [[[UIApplication sharedApplication] visibleViewController].view addSubview:stView];
        [stView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(@40.0f);
            make.left.equalTo(stView.superview).offset(15.0f);
            make.right.equalTo(stView.superview).offset(-15.0f);
            if (@available(iOS 11.0, *)) {
                make.bottom.equalTo(stView.superview.mas_safeAreaLayoutGuideBottom).offset(-15.0f);
            } else {
                make.bottom.equalTo(stView.superview).offset(-15.0f);
            }
        }];
        
        __weak typeof(self) weakSelf = self;
        [stView setHandle:^{
            [[SpeechManager shared] cancel];
            [weakSelf.newsList removeAllObjects];
            weakSelf.newsList = [NSMutableArray array];
            [weakSelf.removedNewsList removeAllObjects];
            weakSelf.removedNewsList = [NSMutableArray array];
            [weakSelf removeStatusView];
        } next:^{
            if ([SpeechManager shared].isPlayDetail) {
                [[SpeechManager shared] cancel];
                [weakSelf speechNewsDetail:weakSelf.newsDetail];
            } else {
                [[SpeechManager shared] cancel];
                [weakSelf autoSpeechNext];
            }
        } pre:^{
            
            //上一个新闻
            [weakSelf preSpeech];
            
        } play:^{
            if ([SpeechManager shared].isPlayDetail) {
                [weakSelf speechNewsDetail:weakSelf.newsDetail];
            } else {
                [weakSelf speech:weakSelf.newsList];
            }
        } tap:^{
            //跳转新闻详情
            UIViewController *controller = [[UIApplication sharedApplication] visibleViewController];
            if ([controller isKindOfClass:[NewsDetailViewController class]]) {
                //当前已经是详情页面
                if ([SpeechManager shared].isPlayDetail) {
                    if ([controller isKindOfClass:[NewsDetailViewController class]] && [[(NewsDetailViewController *)controller urlString] isEqualToString:weakSelf.newsDetail.urlString]) {
                        //不作操作
                    } else {
                        NewsDetailViewController *con = [NewsDetailViewController new];
                        con.urlString = weakSelf.newsDetail.urlString;
                        con.f_thumbnail = weakSelf.newsDetail.f_thumbnail;
                        con.hidesBottomBarWhenPushed = YES;
                        [controller showViewController:con sender:nil];
                    }
                } else {
                    if ([self.newsList count] >0) {
                        M_News *news_ = [weakSelf.newsList objectAtIndex:0];
                        NewsDetailViewController *controller = [NewsDetailViewController new];
                        controller.hidesBottomBarWhenPushed = YES;
                        controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                        controller.f_thumbnail = news_.f_thumbnail;
                        [[[UIApplication sharedApplication] visibleViewController] showViewController:controller sender:nil];
                    }
                }
            } else {
                //当前不是详情页
                if ([SpeechManager shared].isPlayDetail) {
                    NewsDetailViewController *con = [NewsDetailViewController new];
                    con.urlString = weakSelf.newsDetail.urlString;
                    con.f_thumbnail = weakSelf.newsDetail.f_thumbnail;
                    con.hidesBottomBarWhenPushed = YES;
                    [controller showViewController:con sender:nil];
                } else {
                    if ([self.newsList count] >0) {
                        M_News *news_ = [weakSelf.newsList objectAtIndex:0];
                        NewsDetailViewController *controller = [NewsDetailViewController new];
                        controller.hidesBottomBarWhenPushed = YES;
                        controller.urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news_.f_id];
                        controller.f_thumbnail = news_.f_thumbnail;
                        [[[UIApplication sharedApplication] visibleViewController] showViewController:controller sender:nil];
                    }
                }
                
            }  
        }];
        
        [self.detailStatusViews addObject:stView];
    }
    
    //刷新
    NSString *title = @"";
    if ([SpeechManager shared].isPlayDetail) {
        title = self.newsDetail.f_title;
    } else {
        M_News *n = [self.newsList objectAtIndex:0];
        title = n.f_title;
    }
    self.statusView.labelTitle.text = title;
    if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_WORKING) {
        [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
    } else {
        [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
    }
    
    for (NewsSpeechStatusView *v in self.detailStatusViews) {
        v.labelTitle.text = title;
        if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_WORKING) {
            [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
        } else {
            [v.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
        }
    }
    
}

- (void)removeStatusView {
    if (self.statusView) {
        [self.statusView removeFromSuperview];
        self.statusView = nil;
    }
    
    for (UIView *v in self.detailStatusViews) {
        [v removeFromSuperview];
    }
    
    [self.detailStatusViews removeAllObjects];
    self.detailStatusViews = [NSMutableArray array];
}

//MARK: - 播放新闻列表
- (void)speech:(NSArray *)newsList {
    
    if ([SpeechManager shared].isPlayDetail) {
        //直接开始播放
        if (newsList && [newsList count] > 0) {
            if (self.newsList) {
                [self.newsList removeAllObjects];
                [self.removedNewsList removeAllObjects];
            }
            self.newsList = [NSMutableArray arrayWithArray:newsList];
            self.removedNewsList = [NSMutableArray array];
            [self startSpeech];
        }
    } else {
        //判断当前播放状态
        if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_WORKING) {
            //正在播放
            [[SpeechManager shared] pause];
            [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            for (NewsSpeechStatusView *v in self.detailStatusViews) {
                [v.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            }
        } else if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_PAUSED) {
            //暂停
            [[SpeechManager shared] resume];
            [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            for (NewsSpeechStatusView *v in self.detailStatusViews) {
                [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            }
        } else {
            if (newsList && [newsList count] > 0) {
                if (self.newsList) {
                    [self.newsList removeAllObjects];
                    [self.removedNewsList removeAllObjects];
                }
                self.newsList = [NSMutableArray arrayWithArray:newsList];
                self.removedNewsList = [NSMutableArray array];
                [self startSpeech];
            }
        }
    }

}

- (void)startSpeech {
    
    [SpeechManager shared].isPlayDetail = NO;
    
    __weak typeof(self) weakSelf = self;
    //判断是否播放完成,刷新播放界面
    if ([self.newsList count] == 0) {
        //播放完成
        [weakSelf removeStatusView];
    }
    
    //选取第一个，开始播放
    M_News *news = [self.newsList firstObject];
    NSString *urlString = [NSString stringWithFormat:@"%@&aid=%@",URL_SUB_GET_NEWS_DETAIL,news.f_id];
    [ServiceNews doFetchNewsDetail:urlString success:^(id responseObject, NSString *message) {
        M_NewsDetail *detail = responseObject;
        [[SpeechManager shared] speak: [NSString stringWithFormat:@"%@ %@",detail.f_title,detail.f_body] complete:^{
            //播放完成回调,播放下一条
            [weakSelf autoSpeechNext];
        }];
        [weakSelf.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
        weakSelf.statusView.labelTitle.text = detail.f_title;
        for (NewsSpeechStatusView *v in weakSelf.detailStatusViews) {
            [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            v.labelTitle.text = detail.f_title;
        }

    } failure:^(NSString *message) {
        //直接播放下一条
        [weakSelf autoSpeechNext];
    }];
    
    [self showStatusView];
}

- (void)preSpeech {
    if (![SpeechManager shared].isPlayDetail && [self.removedNewsList count] > 0) {
        [self.newsList insertObject:[self.removedNewsList lastObject] atIndex:0];
        [self.removedNewsList removeLastObject];
        [self startSpeech];
    }
}

- (void)autoSpeechNext {
    if ([self.newsList count] >0) {
        [self.removedNewsList addObject:[self.newsList objectAtIndex:0]];
        [self.newsList removeObjectAtIndex:0];
        [self startSpeech];
    } else {
        [self startSpeech];
    }
}

//MARK: - 播放单个新闻
- (void)speechNewsDetail:(M_NewsDetail *)newsDetail {
    
    __weak typeof(self) weakSelf = self;
    
    if ([SpeechManager shared].isPlayDetail) {
        //判断当前播放状态
        if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_WORKING) {
            //正在播放
            [[SpeechManager shared] pause];
            [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            for (NewsSpeechStatusView *v in self.detailStatusViews) {
                [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            }
        } else if ([SpeechManager shared].status == BDS_SYNTHESIZER_STATUS_PAUSED) {
            //暂停
            [[SpeechManager shared] resume];
            [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            for (NewsSpeechStatusView *v in self.detailStatusViews) {
                [v.buttonPlay setImage:[UIImage imageNamed:@"voice_play"] forState:UIControlStateNormal];
            }
        } else {
            //直接播放
            [SpeechManager shared].isPlayDetail = YES;
            [[SpeechManager shared] speak: [NSString stringWithFormat:@"%@ %@",newsDetail.f_title,newsDetail.f_body] complete:^{
                //播放完成
                [weakSelf removeStatusView];
            }];
            [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            self.statusView.labelTitle.text = self.newsDetail.f_title;
            for (NewsSpeechStatusView *v in self.detailStatusViews) {
                [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
                v.labelTitle.text = self.newsDetail.f_title;
            }
            
            self.newsDetail = newsDetail;
        }
    } else {
        //直接播放
        [SpeechManager shared].isPlayDetail = YES;
        [[SpeechManager shared] speak: [NSString stringWithFormat:@"%@ %@",newsDetail.f_title,newsDetail.f_body] complete:^{
            //播放完成
            [weakSelf removeStatusView];
        }];
        [self.statusView.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
        self.statusView.labelTitle.text = self.newsDetail.f_title;
        self.newsDetail = newsDetail;
        for (NewsSpeechStatusView *v in self.detailStatusViews) {
            [v.buttonPlay setImage:[UIImage imageNamed:@"voice_parse"] forState:UIControlStateNormal];
            v.labelTitle.text = self.newsDetail.f_title;
        }
    }
    
    [self showStatusView];

}

@end
